/* eslint-disable */
// @ts-nocheck
'use client';

import { useState, useEffect } from 'react';
import { Plus, Edit2, Trash2, Save, X, Database, Home, RefreshCw } from 'lucide-react';
import { examplesAPI, Example, ExampleCreate, ExampleUpdate } from '@/lib/api';

export default function ExamplesPage() {
  const [examples, setExamples] = useState<Example[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string>('');
  
  // 表单相关状态
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [formData, setFormData] = useState<ExampleCreate>({ name: '', description: '' });

  // 加载数据
  const loadData = async () => {
    try {
      setIsLoading(true);
      setError('');
      const [examplesData, countData] = await Promise.all([
        examplesAPI.getExamples(),
        examplesAPI.getExamplesCount()
      ]);
      setExamples(examplesData);
      setTotalCount(countData.count);
    } catch (err) {
      setError('加载数据失败: ' + (err.message || '未知错误'));
      console.error('加载数据失败:', err);
    } finally {
      setIsLoading(false);
    }
  };

  // 创建示例
  const handleCreate = async () => {
    if (!formData.name.trim()) {
      setError('名称不能为空');
      return;
    }
    
    try {
      setError('');
      await examplesAPI.createExample(formData);
      setFormData({ name: '', description: '' });
      setShowCreateForm(false);
      await loadData(); // 重新加载数据
    } catch (err) {
      setError('创建失败: ' + (err.message || '未知错误'));
    }
  };

  // 更新示例
  const handleUpdate = async (id: number) => {
    if (!formData.name.trim()) {
      setError('名称不能为空');
      return;
    }
    
    try {
      setError('');
      await examplesAPI.updateExample(id, formData);
      setEditingId(null);
      setFormData({ name: '', description: '' });
      await loadData(); // 重新加载数据
    } catch (err) {
      setError('更新失败: ' + (err.message || '未知错误'));
    }
  };

  // 删除示例
  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除这个示例吗？')) return;
    
    try {
      setError('');
      await examplesAPI.deleteExample(id);
      await loadData(); // 重新加载数据
    } catch (err) {
      setError('删除失败: ' + (err.message || '未知错误'));
    }
  };

  // 开始编辑
  const startEdit = (example: Example) => {
    setEditingId(example.id);
    setFormData({ name: example.name, description: example.description || '' });
    setShowCreateForm(false);
  };

  // 取消编辑
  const cancelEdit = () => {
    setEditingId(null);
    setFormData({ name: '', description: '' });
  };

  // 取消创建
  const cancelCreate = () => {
    setShowCreateForm(false);
    setFormData({ name: '', description: '' });
  };

  // 格式化时间
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN');
  };

  useEffect(() => {
    loadData();
  }, []);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 导航栏 */}
      <nav className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center space-x-4">
              <Database className="w-6 h-6 text-blue-600" />
              <h1 className="text-2xl font-bold text-gray-900">Examples 管理</h1>
            </div>
            <div className="flex items-center space-x-2">
              <a 
                href="/" 
                className="flex items-center px-3 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <Home className="w-4 h-4 mr-1" />
                首页
              </a>
              <button
                onClick={loadData}
                disabled={isLoading}
                className="flex items-center px-3 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50"
              >
                <RefreshCw className={`w-4 h-4 mr-1 ${isLoading ? 'animate-spin' : ''}`} />
                刷新
              </button>
            </div>
          </div>
        </div>
      </nav>

      {/* 主要内容 */}
      <main className="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        {/* 错误提示 */}
        {error && (
          <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
            <p className="text-red-700">{error}</p>
          </div>
        )}

        {/* 头部统计和操作 */}
        <div className="mb-6 flex justify-between items-center">
          <div className="flex items-center space-x-4">
            <h2 className="text-xl font-semibold text-gray-900">
              示例列表 ({totalCount} 条记录)
            </h2>
            {isLoading && (
              <div className="flex items-center text-gray-500">
                <RefreshCw className="w-4 h-4 animate-spin mr-1" />
                加载中...
              </div>
            )}
          </div>
          
          <button
            onClick={() => setShowCreateForm(true)}
            disabled={showCreateForm || editingId !== null}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <Plus className="w-4 h-4 mr-2" />
            新建示例
          </button>
        </div>

        {/* 创建表单 */}
        {showCreateForm && (
          <div className="mb-6 p-4 bg-white rounded-lg shadow border">
            <h3 className="text-lg font-medium mb-4">创建新示例</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  名称 *
                </label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入示例名称"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  描述
                </label>
                <input
                  type="text"
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入示例描述"
                />
              </div>
            </div>
            <div className="flex justify-end space-x-2 mt-4">
              <button
                onClick={cancelCreate}
                className="px-4 py-2 text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X className="w-4 h-4 inline mr-1" />
                取消
              </button>
              <button
                onClick={handleCreate}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
              >
                <Save className="w-4 h-4 inline mr-1" />
                保存
              </button>
            </div>
          </div>
        )}

        {/* 示例列表 */}
        <div className="bg-white shadow rounded-lg overflow-hidden">
          {examples.length === 0 && !isLoading ? (
            <div className="p-8 text-center text-gray-500">
              <Database className="w-12 h-12 mx-auto mb-4 text-gray-300" />
              <p>暂无数据，点击"新建示例"创建第一条记录</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      ID
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      名称
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      描述
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      创建时间
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      更新时间
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {examples.map((example) => (
                    <tr key={example.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        {example.id}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {editingId === example.id ? (
                          <input
                            type="text"
                            value={formData.name}
                            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                          />
                        ) : (
                          <span className="text-sm font-medium text-gray-900">{example.name}</span>
                        )}
                      </td>
                      <td className="px-6 py-4">
                        {editingId === example.id ? (
                          <input
                            type="text"
                            value={formData.description}
                            onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                          />
                        ) : (
                          <span className="text-sm text-gray-600">
                            {example.description || '无描述'}
                          </span>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {formatDate(example.created_at)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {example.updated_at ? formatDate(example.updated_at) : '未更新'}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        {editingId === example.id ? (
                          <div className="flex space-x-2">
                            <button
                              onClick={() => handleUpdate(example.id)}
                              className="text-green-600 hover:text-green-900"
                            >
                              <Save className="w-4 h-4" />
                            </button>
                            <button
                              onClick={cancelEdit}
                              className="text-gray-600 hover:text-gray-900"
                            >
                              <X className="w-4 h-4" />
                            </button>
                          </div>
                        ) : (
                          <div className="flex space-x-2">
                            <button
                              onClick={() => startEdit(example)}
                              disabled={editingId !== null || showCreateForm}
                              className="text-blue-600 hover:text-blue-900 disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                              <Edit2 className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => handleDelete(example.id)}
                              disabled={editingId !== null || showCreateForm}
                              className="text-red-600 hover:text-red-900 disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* 页脚信息 */}
        <div className="mt-6 text-center text-sm text-gray-500">
          <p>
            这是一个完整的数据库CRUD操作演示页面。
            <br />
            数据存储在PostgreSQL数据库中，通过FastAPI提供RESTful API。
          </p>
        </div>
      </main>
    </div>
  );
} 